<template>
  <div class="staff-container">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="员工姓名">
          <el-input v-model="searchForm.name" placeholder="请输入员工姓名" clearable/>
        </el-form-item>
        <el-form-item label="所属餐厅">
          <el-select v-model="searchForm.restaurantId" style="width: 150px" placeholder="请选择餐厅" clearable>
            <el-option
              v-for="item in restaurants"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAdd">新增员工</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table v-loading="loading" :data="tableData" border>
        <el-table-column type="index" label="序号" width="60" align="center"/>
        <el-table-column prop="name" label="姓名"/>
        <el-table-column prop="phone" label="手机号"/>
        <el-table-column prop="position" label="职位"/>
        <el-table-column prop="hireDate" label="入职时间">
          <template #default="{ row }">
            {{ formatDate(row.hireDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '在职' : '离职' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="success" link @click="handleStatus(row)">
              {{ row.status === 1 ? '离职' : '在职' }}
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="formData.position" placeholder="请输入职位"/>
        </el-form-item>

        <el-form-item label="入职日期" prop="hireDate">
          <el-date-picker
            v-model="formData.hireDate"
            type="datetime"
            placeholder="选择入职日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="new Date(2000, 1, 1, 0, 0, 0)"
          />
        </el-form-item>

        <el-form-item label="所属餐厅" prop="restaurantId">
          <el-select v-model="formData.restaurantId" placeholder="请选择餐厅">
            <el-option
              v-for="item in restaurants"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">在职</el-radio>
            <el-radio :label="0">离职</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getStaffPage, saveStaff, updateStaff, deleteStaff, updateStaffStatus } from '@/api/staff'
import { getRestaurantPage } from '@/api/restaurant'
import { formatDateTime } from '@/utils/format'
import {formatDate, formatTime} from "@/utils/format";

// 搜索表单
const searchForm = ref({
  name: '',
  restaurantId: ''
})

// 餐厅列表
const restaurants = ref([])

// 获取餐厅列表
const getRestaurants = async () => {
  try {
    const res = await getRestaurantPage({
      pageNum: 1,
      pageSize: 100
    })
    restaurants.value = res.data.records
  } catch (error) {
    console.error('获取餐厅列表失败:', error)
  }
}

// 分页参数
const page = ref({
  current: 1,
  size: 10,
  total: 0
})

// 表格数据
const loading = ref(false)
const tableData = ref([])

// 获取列表数据
const getList = async () => {
  loading.value = true
  try {
    const res = await getStaffPage({
      pageNum: page.value.current,
      pageSize: page.value.size,
      name: searchForm.value.name,
      restaurantId: searchForm.value.restaurantId
    })
    tableData.value = res.data.records
    page.value.total = res.data.total
  } catch (error) {
    console.error('获取列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.value.current = 1
  getList()
}

// 重置
const handleReset = () => {
  searchForm.value.name = ''
  searchForm.value.restaurantId = ''
  handleSearch()
}

// 编辑弹窗
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const formData = ref({
  id: '',
  name: '',
  phone: '',
  position: '',
  status: 1,
  restaurantId: '',
  hireDate: null
})

// 表单校验规则
const formRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  position: [{ required: true, message: '请输入职位', trigger: 'blur' }],
  restaurantId: [{ required: true, message: '请选择所属餐厅', trigger: 'change' }],
  hireDate: [{ required: true, message: '请选择入职日期', trigger: 'change' }]
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增员工'
  dialogVisible.value = true
  formData.value = {
    id: '',
    name: '',
    phone: '',
    position: '',
    status: 1,
    restaurantId: '',
    hireDate: null
  }
}

// 编辑
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑员工'
  dialogVisible.value = true
  formData.value = {
    ...row,
    // 确保日期格式正确
    hireDate: row.hireDate ? formatDateTime(row.hireDate) : null
  }
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除该员工吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteStaff(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

// 更新状态
const handleStatus = (row: any) => {
  const newStatus = row.status === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '在职' : '离职'
  ElMessageBox.confirm(`确定要将该员工状态改为${statusText}吗？`, '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await updateStaffStatus(row.id, newStatus)
      ElMessage.success('状态更新成功')
      getList()
    } catch (error) {
      console.error('状态更新失败:', error)
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate()

  try {
    const submitData = {
      ...formData.value,
      // 确保发送到后端的日期格式正确
      hireDate: formData.value.hireDate ? new Date(formData.value.hireDate).toISOString() : null
    }

    if (formData.value.id) {
      await updateStaff(submitData)
      ElMessage.success('编辑成功')
    } else {
      await saveStaff(submitData)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error('保存失败:', error)
  }
}

// 关闭弹窗
const handleDialogClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  page.value.size = val
  getList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  page.value.current = val
  getList()
}

onMounted(() => {
  getRestaurants()
  getList()
})
</script>

<style scoped>
.staff-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
